﻿using System;
using System.Configuration;
using System.Net;
using System.Threading;
using Cms.Data;
using Cms.Utilities;

namespace Cms.Web.Framework.Infrastructure
{
    public class Scheduler : IDisposable
    {
        private readonly object _syncLock = new object();
        private readonly AutoResetEvent _waitHandle = new AutoResetEvent(false);

        public bool Cancelled { get; set; }
        
        public static void PingServer()
        {
            try
            {
                string domain = Batch.GetDomain();
                var http = new WebClient();
                if (domain == null)
                    return;
                string result = http.DownloadString("http://" + domain + "/Admin/Ping.aspx");
            }
            catch (Exception ex)
            {
                Logging.LogError("PingServer exception", ex);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            Stop();
        }

        #endregion

        public void Start()
        {
            Cancelled = false;
            var t = new Thread(Run);
            t.Start();
        }
        
        public void Stop()
        {
            lock (_syncLock)
            {
                if (Cancelled)
                    return;
                Cancelled = true;
                _waitHandle.Set();
            }
        }

        private void Run()
        {
            int schedulerInterval = string.IsNullOrEmpty(ConfigurationManager.AppSettings["SchedulerInterval"])
                                        ? 300
                                        : int.Parse(ConfigurationManager.AppSettings["SchedulerInterval"]);
            _waitHandle.WaitOne(schedulerInterval * 1000, true);
            while (!Cancelled)
            {
                // Do work here
                Batch.ExecuteScheduledPublishings();

                // ...
                Logging.LogInfo("Scheduler completed " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                PingServer();
                _waitHandle.WaitOne(schedulerInterval * 1000, true);
            }
        }
    }
}